package com.yupi.yupicturehouduan.aop;

import com.yupi.yupicturehouduan.annotation.AuthCheck;
import com.yupi.yupicturehouduan.exception.BusinessException;
import com.yupi.yupicturehouduan.exception.ErrorCode;
import com.yupi.yupicturehouduan.model.entity.User;
import com.yupi.yupicturehouduan.model.enums.UserRoleEnum;
import com.yupi.yupicturehouduan.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public void doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //这个是从接口中获取该接口所需要什么权限来进行判断的
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取用户登录信息
        User user = userService.getLoginUser(request);
        log.info("用户角色:{}",user.getUserRole());
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //如果不需要权限,就放行
        if (mustRoleEnum == null){
            joinPoint.proceed();
        }
        //必须有权限,才让通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(user.getUserRole());
        if (userRoleEnum==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //如果是需要管理员权限的接口，就必须是管理员才能通过
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !userRoleEnum.equals(mustRoleEnum.ADMIN)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        joinPoint.proceed();
    }

}
